package com.hhkj.api.train.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.alibaba.fastjson2.JSON;
import com.hhkj.admin.train.model.extend.TrainCallBackRes;
import com.hhkj.admin.train.model.req.TrainReq;
import com.hhkj.api.train.common.cont.ApiTrainCallBackConst;
import com.ruoyi.common.cont.user.UserConst;
import com.hhkj.api.common.session.holder.model.LoginStudent;
import lombok.extern.slf4j.Slf4j;

/**
 * ApiTrainCallBackUtils
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2023/7/15 0:06
 */
@Slf4j
public class ApiTrainCallBackUtils
{
    /**
     * 向外推送考试结果信息
     *
     * @param loginStudent 登录学生信息
     * @param trainReq     培训信息
     */
    public static void push(LoginStudent loginStudent, TrainReq trainReq)
    {
        if (!UserConst.UserType.OPEN.getCode().equals(loginStudent.getCreateByUserType())) {
            return;
        }
        if (StrUtil.isBlank(loginStudent.getTrainCallBackApi()) || ObjectUtil.isNull(loginStudent.getOrigSysId())) {
            return;
        }
        TrainCallBackRes trainCallBackRes = BeanUtil.toBean(trainReq, TrainCallBackRes.class);
        trainCallBackRes.setStudentOrigSysId(loginStudent.getOrigSysId());
        HttpRequest httpRequest = HttpRequest.of(loginStudent.getTrainCallBackApi()).method(Method.POST);
        httpRequest.body(JSON.toJSONString(trainCallBackRes));
        boolean callBackResult = false;
        for (int i = 0; i < 5; i++) {
            HttpResponse httpResponse = httpRequest.execute();
            if (httpResponse.isOk()) {
                log.info(httpResponse.body());
                if (ApiTrainCallBackConst.REQUEST_RETURN_SUCCESS.equals(httpResponse.body())) {
                    callBackResult = true;
                    break;
                } else {
                    log.info("回调信息请求成功，但是返回信息失败！");
                }
            }
        }
        if (!callBackResult) {
            log.info("回调信息发送失败！");
        }
    }
}
